/**
 * Created by Administrator on 2018/8/28.
 */
var triArray = new Array();
var insideGrid;
var startGridTwo;
var $$scope;
var codeNow = "";
var tempOriginSelect;


// 报销费用明细
var afrColumnsbsb = [{
    id: 'trCompanyName',
    title: '报销主体公司',
    width: 150,
    type: 'string',
    columnClass: 'text-center',
}, {
    id: 'triClassName',
    title: '报销类目',
    width: 150,
    type: 'string',
    columnClass: 'text-center',
}, {
    id: 'money',
    title: '金额',
    type: 'string',
    width: 100,
    columnClass: 'text-center',
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        var content = '￥' + value + '元';
        return content;
      }
}, {
    id: 'startDate',
    title: '开始日期',
    type: 'string',
    width: 150,
    hideType: 'lg|md|sm|xs',
    columnClass: 'text-center',
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        var date = new Date(record.startDate);
        var content = $.fn.dlshouwen.grid.tools.dateFormat(date, "yyyy-MM-dd");
        return content;
    }
}, {
    id: 'endDate',
    title: '结束日期',
    type: 'string',
    width: 150,
    hideType: 'lg|md|sm|xs',
    columnClass: 'text-center',
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        var date = new Date(record.endDate);
        var content = $.fn.dlshouwen.grid.tools.dateFormat(date, "yyyy-MM-dd");
        return content;
    }
}, {
    id: 'startAddr',
    title: '开始地点',
    type: 'string',
    width: 150,
    hideType: 'lg|md|sm|xs',
    columnClass: 'text-center',
}, {
    id: 'endAddr',
    title: '结束地点',
    type: 'string',
    width: 150,
    hideType: 'lg|md|sm|xs',
    columnClass: 'text-center',
}, {
    id: 'triNum',
    title: '原始单据数量',
    type: 'string',
    width: 100,
    hideType: 'lg|md|sm|xs',
    columnClass: 'text-center',
}, {
    id: 'trInstruction',
    title: '费用报销明细说明',
    type: 'string',
    columnClass: 'text-left',
}, {
    id: 'operation',
    title: '操作',
    width: 100,
    type: 'string',
    columnClass: 'text-center',
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        var content = '';
        content += '  ';
        content += '<button class="btn btn-xs btn-primary" onclick="disMyModal(\'' + record.triCode + '\');"><i class="icon-eye-open"></i>  项目占比</button>';
        return content;
    }
}];
var afrOptionbsb = {
    lang: 'zh-cn',
    ajaxLoad: false,
    extraWidth: 20,
    // loadURL:'url',
    exportFileName: '报销费用明细',
    datas: [],
    columns: afrColumnsbsb,
    gridContainer: 'afrContainerbsb',
    toolbarContainer: 'afrToolBarContainerbsb',
    tools: '',
    pageSize: 10,
    pageSizeLimit: [10, 15, 20]
};

var nowprojectPercent;
var projIdNow;
$$scope.trEntity = {};
triArray = new Array();
$$scope.trEntity = {
    trCode: "tr-" + new Date().getTime() + Math.floor(Math.random() * 10000),
    items: triArray
};
$$scope.getsssbbb = function (bb) {
    ;
    //starting denied sentback others completed
    if (bb == "starting") {
        return "正在进行中";
    } else if (bb == "denied") {
        return "否决";
    } else if (bb == "sentback") {
        return "被退";
    } else if (bb == "others") {
        return "关闭";
    } else if (bb == "completed") {
        return "完成";
    } else if (bb == "terminated") {
        return "终结";
    } else if (bb == "cancelled") {
        return "通过";
    }
    return "待办";
}
$$scope.triPercentDis = true;

$CertusJsonAjax.ajax("queryEveryProjTrace", {
    "processInstanceId": $CertusJsonAjax.getProInstanceId(),
    "stepInstanceId": $CertusJsonAjax.getStepInstanceId()
}, function (res) {

    $$scope.projs = res.data;
})

$CertusJsonAjax.ajax("openCCBXLCbsb", {
    "processInstanceId": $CertusJsonAjax.getProInstanceId(),
    "stepInstanceId": $CertusJsonAjax.getStepInstanceId()
}, function (res) {

    if (res.data) {
        $$scope.trEntity = res.data;
        if ($$scope.trEntity.travelCode && $$scope.trEntity.travelCode != "") {
            $$scope.travelCodeChange($$scope.trEntity.travelCode);
        }

        triArray = res.data.items;
        var afrOptionbsb = {
            lang: 'zh-cn',
            ajaxLoad: false,
            extraWidth: 20,
            // loadURL:'url',
            exportFileName: '报销费用明细',
            datas: res.data.items,
            columns: afrColumnsbsb,
            gridContainer: 'afrContainerbsb',
            toolbarContainer: 'afrToolBarContainerbsb',
            tools: '',
            pageSize: 10,
            pageSizeLimit: [10, 15, 20]
        };
        startGridTwo = $.fn.dlshouwen.grid.init(afrOptionbsb);
        startGridTwo.load();
        startGridTwo.exhibitDatas = triArray;
        startGridTwo.refresh(false);
    }
})

var picker3 = $('#dateTime1').datetimepicker({
    format: 'YYYY-MM-DD',
    locale: moment.locale('zh-cn')
}).on('dp.change', function (e) {
    var result = new moment(e.date).format('YYYY-MM-DD');
    if (result && !angular.isUndefined(result)) {
        $$scope.trItem.startDate = result;
        $$scope.$apply();
    }
})

var picker4 = $('#dateTime2').datetimepicker({
    format: 'YYYY-MM-DD',
    locale: moment.locale('zh-cn')
}).on('dp.change', function (e) {
    var result = new moment(e.date).format('YYYY-MM-DD');
    if (result && !angular.isUndefined(result)) {
        $$scope.trItem.endDate = result;
        $$scope.$apply();
    }
})

//报销 条目
$$scope.ccClassSelect = [{
        name: "火车/汽车",
        code: "train"
    },
    {
        name: "飞机",
        code: "plan"
    },
    {
        name: "交通费用",
        code: "traffic"
    },
    {
        name: "住宿费用",
        code: "hotel"
    },
    {
        name: "招待费",
        code: "repetition"
    },
    {
        name: "其他费用",
        code: "others"
    },
    {
        name: "出差补助",
        code: "travelAllowance"
    }
]

$$scope.ccCompanySelect = [{
        name: "赛特斯集团",
        code: "STSJT"
    },
    {
        name: "赛特斯南京",
        code: "STSNJ"
    },
    {
        name: "赛特斯广州",
        code: "STSGD"
    },
    {
        name: "赛特斯北京",
        code: "STSBJ"
    },
]

//选取 可以 直接 使用 的出差单号
$CertusFormAjax.ajax("availablePolicyNumber", {}, function (res) {
    if (res.data) {
        $$scope.availablePolicyNumberSelect = res.data;
    }
})
$$scope.travelCodeChange = function (a) {
    if (a) {
        for (var j in triArray) {
            triArray[j].projectPercent = null;
        }
        //初始化可以选取的 项目编号
        $CertusFormAjax.ajax("availableProjNumber", {
            travelCode: a
        }, function (res) {
            if (res.data) {
                $$scope.availableProjNumberSelect = res.data;
                tempOriginSelect = res.data;
            }
        })
        $$scope.triPercentDis = false;
        return;
    }
    $$scope.triPercentDis = true;

}

$$scope.addItem = function () {

    $$scope.trItem = {};

    $(".afrinfo").show();
}

$$scope.saveDraftCCBX = function () {
    $CertusJsonAjax.ajax("saveDraftCCBX", $$scope.trEntity, function (res) {
        if (res.data) {
            if (res.data == "success") {
                window.history.back();
            }
        }
    })
}

$CertusJsonAjax.ajax("queryCCBXLCProcessTrace", {
    "processInstanceId": $CertusJsonAjax.getProInstanceId(),
    "stepInstanceId": $CertusJsonAjax.getStepInstanceId()
}, function (res) {
    $$scope.processCCBXTrace = res.data;
})

$$scope.startCCBXLc = function () {
    // $$scope.trEntity.tmpProcessInstanceId = $CertusJsonAjax.getProInstanceId();
    // $$scope.trEntity.tmpStepInstanceId = $CertusJsonAjax.getStepInstanceId();

    $CertusJsonAjax.ajax("startCCBXLc", $$scope.trEntity, function (res) {
        if (res.data) {
            if (res.data.succed == "success") {
                nextApprovalManView(res.data.tip);
                window.history.back();
                return;
            }
            layer.msg(res.data.succed);
        }
    })
}

function isDifferentPercent(element) {
    return element.projId != projIdNow;
}


$$scope.percentSubmit = function (a) {
    projIdNow = a;
    for (var ii in $$scope.availableProjNumberSelect) {
        if ($$scope.availableProjNumberSelect[ii].code == a) {
            $$scope.triPercent.projName = $$scope.availableProjNumberSelect[ii].name
        }
    }
    if (nowprojectPercent) {
        for (var i in nowprojectPercent) {
            if (nowprojectPercent[i].projId == a) {
                nowprojectPercent[i] = $$scope.triPercent;
            }
        }

        nowprojectPercent = nowprojectPercent.filter(isDifferentPercent);
        nowprojectPercent.push($$scope.triPercent);
        for (var h in triArray) {
            if (triArray[h].triCode == codeNow) {
                triArray[h].projectPercent = nowprojectPercent;
                triArray[h].originSurplus -= $$scope.triPercent.money
            }
        }
    }
    $(".haddpro").hide();
}

$$scope.disDraft = function () {
    $("#yourModal").modal('show');
}

$$scope.itemSubmit = function () {

    if (certusValidateNotnullPolyfill()) {
        var changeTr = {};

        //补足 name
        for (var j in $$scope.ccCompanySelect) {
            if ($$scope.ccCompanySelect[j].code == $$scope.trItem.trCompanyCode) {
                $$scope.trItem.trCompanyName = $$scope.ccCompanySelect[j].name;
            }
        }

        for (var k in $$scope.ccClassSelect) {
            if ($$scope.ccClassSelect[k].code == $$scope.trItem.triClassCode) {
                $$scope.trItem.triClassName = $$scope.ccClassSelect[k].name;
            }
        }
        if ($$scope.trItem.projectPercent) {
            $$scope.trItem.originSurplus = $$scope.trItem.money;
            for (var i in $$scope.trItem.projectPercent) {
                $$scope.trItem.originSurplus -= $$scope.trItem.projectPercent[i].money;
            }
        };
        if ($$scope.trItem.originSurplus < 0) {
            layer.msg("目前项目分配钱，已经超过现有的总和");
            return;
        }
        $$scope.trItem.trCode = $$scope.trEntity.trCode;
        $$scope.trItem.triCode = "tri-" + new Date().getTime() + Math.floor(Math.random() * 10000);
        codeNow = $$scope.trItem.triCode;
        triArray = triArray.filter(isDifferent);
        triArray.push($$scope.trItem);
        //算出总金额
        $$scope.trEntity.totalAmount = 0;
        for (var b in triArray) {
            $$scope.trEntity.totalAmount += triArray[b].money;
        }
        startGridTwo.exhibitDatas = triArray;
        $$scope.trEntity.items = triArray;
        startGridTwo.refresh(false);

        $(".afrinfo").hide();
    }
}


$$scope.closeAddItem = function () {
    $(".afrinfo").hide();
}


$$scope.triPercentChange = function (a) {
    if (a) {
        for (var i in triArray) {
            if (triArray[i].triCode == codeNow) {
                var number = parseInt(triArray[i].originSurplus) - parseInt(a);
                $$scope.triPercent
            }
        }
        $$scope.triPercent.surplus = number;
        return
    }
    $$scope.triPercent.surplus = $$scope.originSurplus
}

$$scope.editPercent = function (projId) {
    for (var i in triArray) {
        if (triArray[i].triCode == codeNow) {
            for (var j in triArray[i].projectPercent) {

                $$scope.triPercent = triArray[i].projectPercent[j];
                triArray[i].originSurplus += triArray[i].projectPercent[j].money;
                $("#myModal").modal('hide');
                $(".haddpro").show();
            }
        }
    }
}

$$scope.delPercent =
    function (projId) {
        // layer.confirm('确认删除此数据？', {
        //     btn: ['确认', '取消'] //按钮
        // }, function () {
            for (var j in triArray) {
                if (triArray[j].triCode == codeNow) {
                    for (var i in triArray[j].projectPercent) {
                        if (triArray[j].projectPercent[i].projId == projId) {
                            projIdNow == projId;
                            triArray[j].originSurplus += triArray[j].projectPercent[i].money;
                            triArray[j].projectPercent = triArray[j].projectPercent.filter(isDiffPercent);
                            $$scope.nowprojectPercents = triArray[j].projectPercent;
                            return;
                        }
                    }
                }
            }
        //     layer.msg('删除成功');
        // });
       
    }


function delTriItem(triCode) {
    layer.confirm('确认删除此数据？', {
        btn: ['确认', '取消'] //按钮
    }, function () {
        for (var i in triArray) {
            if (triArray[i].triCode == triCode) {
                triArray = triArray.filter(isDifferent);
                startGridTwo.exhibitDatas = triArray;
                startGridTwo.refresh(false);
                $$scope.trEntity.items = triArray;
            }
        }
        layer.msg('删除成功');
    });
    
}


function disMyModal(triCode) {
    ;
    for (var i in triArray) {
        if (triArray[i].triCode == triCode) {
            if (triArray[i].projectPercent) {
                codeNow = triCode;
                nowprojectPercent = triArray[i].projectPercent;
                $$scope.trItem = triArray[i];
                $$scope.nowprojectPercents = nowprojectPercent;
                $$scope.$apply();
                $("#myModal").modal('show');
                // $(".haddpro").show();
            }
        }
    }
}

function isDifferentSelect(element) {
    return element.code != projIdNow;
}





function editCC(triCode) {
    for (var i in triArray) {
        if (triArray[i].triCode == triCode) {
            $$scope.trItem = triArray[i];
            $$scope.trItem.startDate = $$filter("date")($$scope.trItem.startDate, "yyyy-MM-dd");
            $$scope.trItem.endDate = $$filter("date")($$scope.trItem.endDate, "yyyy-MM-dd");
            $$scope.$apply();
        }
        T
        $(".afrinfo").show();
    }
}

function isDifferent(element) {
    return element.triCode != codeNow;
}


function isDiffPercent(element) {
    return element.projId != projIdNow;
}